import {ScrollView, View, Text, Image, Video, Button} from '@tarojs/components';
import React, {Component} from 'react';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import moment from 'dayjs';
import Blank from '@/pages/common/blank';
import api from 'api';
import nones from '@/assets/image/none/nones.png';
import {
  AtFloatLayout,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtActionSheet,
  AtActionSheetItem,
} from 'taro-ui';
import 'taro-ui/dist/style/components/action-sheet.scss';
import 'taro-ui/dist/style/components/float-layout.scss';
import 'taro-ui/dist/style/components/modal.scss';
import certified from '@/assets/image/myPost/certified.png';
import n_certified from '@/assets/image/myPost/n_certified.png';
import reviewImg from '@/assets/image/myPost/review.png';
import errorImg from '@/assets/image/myPost/error.png';
import successImg from '@/assets/image/myPost/success.png';
import share from '@/assets/image/community/share.png';
import write from '@/assets/image/community/write.png';
import zan from '@/assets/image/community/zan.png';
import zanCurr from '@/assets/image/community/zan-curr.png';
import trashImg from '@/assets/image/index/trash.png';
import more from '@/assets/image/community/more.png';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      tabList: [
        {status: 0, text: '我的发布'},
        {status: 1, text: '我的赞'},
        {status: 2, text: '我的评论'},
      ],
      curNow: 0, //tab状态,对应处理状态status
      userInfo: {},
      isShow: false, //删除弹窗
      isDeleteForum: false, //删除帖子
      isDeleteComment: false, //删除评论
      forumData: {}, //选中数据
      index: '', //选中数据的下标
      refresherTriggered: false,
      clickLikeVal: false,
    };
  }

  componentDidMount() {}

  componentDidShow() {
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (itemStr) {
      this.setState({userInfo: itemStr.user}, () => {
        this.props.actions.init(this.state.curNow);
      });
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  changeTabs(item) {
    this.setState({curNow: item.status, isShow: false}, () => {
      this.props.actions.action.commonChange('main.myPostList', []);
      this.props.actions.action.commonChange('main.pageNum', 1);
      this.props.actions.action.commonChange('main.totalPages', 1);
      this.props.actions.action.getPostList(item.status);
    });
  }

  tabList(list) {
    let listView = [];
    let {curNow} = this.state;
    list.map((item) => {
      listView.push(
        <View
          className="t_view"
          onClick={() => {
            this.changeTabs(item);
          }}
        >
          <Text className={curNow == item.status ? 't_a_text' : 't_text'}>{item.text}</Text>
          <View className={curNow == item.status ? 't_a_border' : 't_border'}></View>
        </View>,
      );
    });
    return listView;
  }

  //数据列表
  renderList(list) {
    let {
      actions: {action},
    } = this.props;
    let {curNow} = this.state;
    let listView = [];
    list.map((item, index) => {
      if (curNow == 2) {
        //我的评论
        listView.push(
          <View
            className="postViews"
            onClick={(e) => {
              e.stopPropagation();
              this.navPostDetail(item, false);
            }}
          >
            <View className="R_SB" style={{marginBottom: '5rpx'}}>
              <View />
              <View
                className="R"
                style={{
                  flexDirection: 'row',
                  justifyContent: 'flex-end',
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  this.setState({
                    forumData: item,
                    index,
                    isDeleteComment: true,
                  });
                }}
              >
                <View className="f_center">
                  <Image
                    style={{
                      width: '40rpx',
                      height: '40rpx',
                    }}
                    src={trashImg}
                  />
                </View>
              </View>
            </View>
            <View
              style={{
                backgroundColor: '#F7F7F7',
                marginTop: '15rpx',
                padding: '20rpx',
              }}
            >
              <View className="R">
                <View
                  style={{
                    width: '75rpx',
                    height: '75rpx',
                    borderRadius: '35rpx',
                    overflow: 'hidden',
                  }}
                >
                  <Image
                    style={{
                      width: '75rpx',
                      height: '75rpx',
                    }}
                    src={item.userImg}
                    mode="aspectFill"
                  />
                </View>
                <View className="C_SB" style={{marginLeft: '15rpx'}}>
                  <View className="R">
                    <Text style={{fontSize: '24rpx', color: '#333333'}}>{item.userName}</Text>
                  </View>
                  <View className="R">
                    <Text className="f_date">{moment(item.date).format('YYYY-MM-DD')}</Text>
                  </View>
                </View>
              </View>
              <View style={{marginTop: '5rpx'}}>
                <Text className="text" style={{fontSize: '22rpx'}}>
                  {item.content}
                </Text>
              </View>
            </View>
            <View style={{marginTop: '30rpx'}}>{this.renderComment(item.commentList)}</View>
          </View>,
        );
      } else {
        listView.push(
          <View
            className="postViews"
            onClick={(e) => {
              e.stopPropagation();
              this.navPostDetail(item, false);
            }}
          >
            {curNow == 0 ? ( //我的发布
              <View
                className="R_SB"
                style={{
                  flexDirection: 'row',
                  alignItems: 'flex-start',
                  position: 'relative',
                }}
              >
                {item.status == 0 ? ( //待审核
                  <Image className="reviewImg" src={reviewImg} mode="widthFix" />
                ) : item.status == 1 ? ( //审核通过
                  <Image className="reviewImg" src={successImg} mode="widthFix" />
                ) : item.status == 2 ? ( //审核不通过
                  <Image className="reviewImg" src={errorImg} mode="widthFix" />
                ) : null}
                <View className="R">
                  <Image
                    style={{
                      width: '75rpx',
                      height: '75rpx',
                      borderRadius: '35rpx',
                      overflow: 'hidden',
                    }}
                    src={item.userImg}
                    mode="aspectFill"
                  />
                  <View className="C_SB" style={{marginLeft: '15rpx'}}>
                    <View className="R">
                      <Text className="f_28">{item.userName}</Text>
                    </View>
                    <View className="R">
                      <Text className="f_date">{moment(item.publishDate).format('YYYY-MM-DD')}</Text>
                    </View>
                  </View>
                </View>
                <View className="R">
                  <View
                    className="f_center"
                    onClick={(e) => {
                      e.stopPropagation();
                      this.setState({
                        isShow: true,
                        forumData: item,
                        index,
                      });
                    }}
                  >
                    <Image
                      style={{
                        width: '36rpx',
                        height: '36rpx',
                      }}
                      src={more}
                    />
                  </View>
                </View>
              </View>
            ) : curNow == 1 ? ( //我的赞
              <View className="R_SB">
                <View className="R">
                  <Image
                    style={{
                      width: '75rpx',
                      height: '75rpx',
                      borderRadius: '35rpx',
                      overflow: 'hidden',
                    }}
                    src={item.userImg}
                    mode="aspectFill"
                  />
                  <View className="C_SB" style={{marginLeft: '15rpx'}}>
                    <View className="R">
                      <Text className="f_28">{item.userName}</Text>
                      {item.unionId && item.unionId != '' ? (
                        <View className="f_center">
                          <Image className="icon" src={certified} />
                        </View>
                      ) : (
                        <View className="f_center">
                          <Image className="icon" src={n_certified} />
                        </View>
                      )}
                    </View>
                    <View className="R">
                      <Text className="f_date">{moment(item.publishDate).format('YYYY-MM-DD')}</Text>
                    </View>
                  </View>
                </View>
              </View>
            ) : null}
            {item.content ? (
              <View style={{marginTop: '20rpx'}}>
                <Text className="text">{item.content}</Text>
              </View>
            ) : null}
            <View className="R_W">
              {item.videoImg && item.videoUrl ? (
                <View className="imgItem">
                  <Video
                    className="video"
                    src={item.videoUrl}
                    initialTime={0}
                    controls
                    autoplay={false}
                    loop={false}
                    muted={false}
                  />
                </View>
              ) : null}
              {item.url != '' && item.url ? this.renderImg(item.url.split(';')) : null}
            </View>
            <View
              className="R_SB"
              style={{
                alignItems: 'center',
                marginTop: '30rpx',
              }}
            >
              <View />
              <View style={{width: '100%', flexDirection: 'row'}}>
                <View
                  className="f_center"
                  style={{flex: 1}}
                  onClick={(e) => {
                    e.stopPropagation();
                    if (item.status == 0) {
                      Taro.showToast({
                        title: '帖子审核中，暂不支持操作！',
                        icon: 'none',
                        duration: 2000,
                      });
                      return;
                    } else if (item.status == 1) {
                      Taro.setStorageSync('postDetail', item);
                      action.commonChange('main.showMode', true);
                    } else if (item.status == 2) {
                      Taro.showToast({
                        title: '帖子审核未通过，暂不支持操作！',
                        icon: 'none',
                        duration: 2000,
                      });
                      return;
                    }
                  }}
                >
                  <Image className="b_icon" src={share} />
                  <View className="f_center" style={{marginLeft: '15rpx'}}>
                    <Text className="num">分享</Text>
                  </View>
                </View>
                <View
                  onClick={(e) => {
                    e.stopPropagation();
                    if (item.status == 0) {
                      Taro.showToast({
                        title: '帖子审核中，暂不支持操作！',
                        icon: 'none',
                        duration: 2000,
                      });
                      return;
                    } else if (item.status == 1) {
                      this.navPostDetail(item, true);
                    } else if (item.status == 2) {
                      Taro.showToast({
                        title: '帖子审核未通过，暂不支持操作！',
                        icon: 'none',
                        duration: 2000,
                      });
                      return;
                    }
                  }}
                  className="f_center"
                  style={{flex: 1}}
                >
                  <Image className="b_icon" src={write} />
                  <View className="f_center" style={{marginLeft: '15rpx'}}>
                    <Text className="num">{item.commentNum}</Text>
                  </View>
                </View>
                <View
                  onClick={(e) => {
                    e.stopPropagation();
                    if (item.status == 0) {
                      Taro.showToast({
                        title: '帖子审核中，暂不支持操作！',
                        icon: 'none',
                        duration: 2000,
                      });
                      return;
                    } else if (item.status == 1) {
                      this.LikeClick(item, index, item.thumbFlag);
                    } else if (item.status == 2) {
                      Taro.showToast({
                        title: '帖子审核未通过，暂不支持操作！',
                        icon: 'none',
                        duration: 2000,
                      });
                      return;
                    }
                  }}
                  className="f_center"
                  style={{flex: 1}}
                >
                  {item.thumbFlag ? <Image className="b_icon" src={zan} /> : <Image className="b_icon" src={zanCurr} />}
                  <View className="f_center" style={{marginLeft: '15rpx'}}>
                    <Text className="num">{item.thumbNum}</Text>
                  </View>
                </View>
              </View>
            </View>
          </View>,
        );
      }
    });
    return listView;
  }

  //点赞、取消点赞
  async LikeClick(item, index, type) {
    let {clickLikeVal, curNow} = this.state;
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (clickLikeVal) {
      return;
    }
    this.setState(
      {
        clickLikeVal: true,
      },
      () => {
        let {
          main: {myPostList},
          actions: {action},
        } = this.props;
        if (type) {
          //点赞后处理
          myPostList[index].thumbFlag = !type;
          myPostList[index].thumbNum += 1;
          action.commonChange('main.myPostList', myPostList);
        } else {
          //取消点赞后处理
          myPostList[index].thumbFlag = !type;
          myPostList[index].thumbNum -= 1;
          action.commonChange('main.myPostList', myPostList);
        }
        let params = {
          userId: itemStr.user.id,
          targetId: item.id,
          type: 1,
        };
        if (type) {
          //点赞
          action.addThumb(params);
        } else {
          //取消点赞
          action.deleteThumb(params);
        }
        setTimeout(() => {
          this.props.actions.init(curNow);
          this.setState({
            clickLikeVal: false,
          });
        }, 300);
      },
    );
  }

  //详情
  navPostDetail(item, type) {
    Taro.navigateTo({
      url: `/pages/package-B/community-detail/index?id=${item.id}&type=${type}`,
    });
  }

  //评论列表
  renderComment(commentList) {
    let list = [];
    if (commentList) {
      commentList.map((item, index) => {
        list.push(
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                color: '#333333',
                fontSize: '26rpx',
              }}
            >
              <View
                style={{
                  width: '50rpx',
                  height: '50rpx',
                  borderRadius: '50rpx',
                  overflow: 'hidden',
                }}
              >
                <Image
                  style={{
                    width: '50rpx',
                    height: '50rpx',
                  }}
                  mode="aspectFill"
                  src={this.state.userInfo.pictureUrl}
                />
              </View>
              <Text
                style={{
                  marginLeft: '4rpx',
                  fontSize: '24rpx',
                }}
              >
                {this.state.userInfo.name}
              </Text>
            </View>
            <Text
              style={{
                fontSize: '24rpx',
              }}
            >
              {moment(item.date).format('YYYY-MM-DD')}
            </Text>
          </View>,
          <Text
            style={{
              color: '#333333',
              fontSize: '26rpx',
              marginTop: '20rpx',
              marginBottom: '20rpx',
              borderBottomColor: '#efefef',
              borderBottomWidth: 1,
              paddingBottom: '20rpx',
              lineHeight: '36rpx',
            }}
          >
            回复:&nbsp;&nbsp;{item.content}
          </Text>,
        );
      });
    }
    return list;
  }

  //图片渲染
  renderImg(list) {
    let listView = [];
    let urls = [];
    if (list.length > 0) {
      list.map((item, index) => {
        urls.push(item);
        listView.push(
          <View className="imgItem">
            <Image
              key={item}
              onClick={this.onImageClick.bind(this, item, urls)}
              src={item}
              mode="aspectFill"
              className="b_img"
            />
          </View>,
        );
      });
    }
    return listView;
  }
  onImageClick = (item, urls) => {
    this.previewImage(item, urls);
  };
  previewImage = (img, files) => {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: files, // 需要预览的图片http链接列表
    });
  };

  async deleteForum() {
    let {
      main: {myPostList},
      actions: {action},
    } = this.props;
    let {userInfo, forumData, index} = this.state;
    let params = {
      delUser: userInfo.id,
      id: forumData.id,
    };
    let result = await api.forumController.deleteForum(params);
    if (result.success) {
      Taro.showToast({
        title: '删除成功！',
        icon: 'none',
        duration: 2000,
      });
      myPostList.splice(index, 1);
      action.commonChange('main.myPostList', JSON.parse(JSON.stringify(myPostList)));
    }
  }

  async deleteComment() {
    let {
      main: {myPostList},
      actions: {action},
    } = this.props;
    let {userInfo, forumData, index} = this.state;
    let params = {
      userId: userInfo.id,
      forumId: forumData.id,
    };
    let result = await api.forumController.deleteComment(params);
    if (result.success) {
      Taro.showToast({
        title: '删除成功！',
        icon: 'none',
        duration: 2000,
      });
      myPostList.splice(index, 1);
      action.commonChange('main.myPostList', JSON.parse(JSON.stringify(myPostList)));
    }
  }

  _onScrollToLower = () => {
    let {curNow} = this.state;
    let {
      main: {pageNum, totalPages},
      actions: {action},
    } = this.props;
    let num = pageNum + 1;
    if (pageNum == totalPages) return;
    this.props.actions.action.commonChange('main.pageNum', num);
    this.props.actions.action.getPostList(curNow);
  };

  _onRefresherRefresh = () => {
    let {refresherTriggered, curNow} = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    this.props.actions.action.commonChange('main.pageNum', 1);
    this.props.actions.action.getPostList(curNow);
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  onShareAppMessage = (res) => {
    let {user} = Taro.getStorageSync('b2b-wechat@login');
    let detail = Taro.getStorageSync('postDetail');
    let arr = [];
    let path = `/pages/package-B/community-detail/index?id=${detail.id}&del=false`;
    let title = `【${user.name}】为您推荐`;
    let imageUrl = `https://shang-cloud.oss-cn-nanjing.aliyuncs.com/assets/image/none/share.png`;
    if (detail.url) {
      arr = detail.url.split(';');
      imageUrl = arr[0];
    }
    if (res.from === 'button') {
      //页面内分享按钮
      return {
        title,
        imageUrl,
        path,
      };
    }
  };

  render() {
    let {refresherTriggered, tabList, curNow, isShow, isDeleteForum, isDeleteComment} = this.state;
    let {
      main: {myPostList, pageNum, totalPages, isLoading, showMode},
      actions: {action},
    } = this.props;
    return (
      <View className="packageCMyPost">
        <View className="t_row">{this.tabList(tabList)}</View>
        <ScrollView
          className="scrollView"
          onScrollToLower={this._onScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggered}
          onRefresherPulling={this._onRefresherRefresh}
          scrollY
        >
          {myPostList.length > 0 ? (
            this.renderList(myPostList)
          ) : (
            <Blank
              content={curNow == 0 ? '您还没有发布过帖子~' : curNow == 1 ? '您还没有点过赞~' : '您还没有评论过帖子~'}
              img={nones}
              imgStyle={{width: '343rpx', height: '288rpx'}}
              textStyle={{
                fontSize: '28rpx',
                color: '#BFBFBF',
                textAlign: 'center',
                marginTop: '40rpx',
              }}
            />
          )}
          {myPostList.length != 0 && pageNum != totalPages && <View className="status">加载中</View>}
          {!isLoading && myPostList.length != 0 && pageNum == totalPages && <View className="status">已经到底了~</View>}
        </ScrollView>
        {/* 删除 */}
        <AtFloatLayout isOpened={isShow}>
          <View className="atfloatItem">
            <View
              className="atfloatFeatl"
              onClick={(e) => {
                e.stopPropagation();
                this.setState({
                  isDeleteForum: true,
                  isShow: false,
                });
              }}
            >
              删除
            </View>
            <View className="atfloatLine"></View>
            <View
              className="atfloatCancle"
              onClick={(e) => {
                e.stopPropagation();
                this.setState({
                  isShow: false,
                });
              }}
            >
              取消
            </View>
          </View>
        </AtFloatLayout>
        {/* 删除帖子确认弹窗 */}
        <AtModal
          isOpened={isDeleteForum}
          title="温馨提示"
          cancelText="取消"
          confirmText="确定"
          onClose={() => {
            this.setState({
              isDeleteForum: false,
            });
          }}
          onCancel={() => {
            this.setState({
              isDeleteForum: false,
            });
          }}
          onConfirm={() => {
            this.setState(
              {
                isDeleteForum: false,
              },
              () => {
                this.deleteForum();
              },
            );
          }}
          content="是否确定将此帖子删除？"
        />
        {/* 删除评论确认弹窗 */}
        <AtModal
          isOpened={isDeleteComment}
          title="温馨提示"
          cancelText="取消"
          confirmText="确定"
          onClose={() => {
            this.setState({
              isDeleteComment: false,
            });
          }}
          onCancel={() => {
            this.setState({
              isDeleteComment: false,
            });
          }}
          onConfirm={() => {
            this.setState(
              {
                isDeleteComment: false,
              },
              () => {
                this.deleteComment();
              },
            );
          }}
          content="是否确认删除这条评论？"
        />
        <AtActionSheet
          isOpened={showMode}
          cancelText="取消"
          onCancel={() => action.commonChange('main.showMode', false)}
          onClose={() => action.commonChange('main.showMode', false)}
        >
          {/* @ts-ignore */}
          <AtActionSheetItem
            onClick={() => {
              action.commonChange('main.showMode', false);
            }}
          >
            <Button openType="share" className="pageMyCollectionE-sharebtn">
              分享
            </Button>
          </AtActionSheetItem>
        </AtActionSheet>
      </View>
    );
  }
}
